<template>
  <div>
    <van-nav-bar title="添加联系人" left-text="返回" left-arrow fixed safe-area-inset-top placeholder @click-left="onClickLeft"/>
    <div style="margin-top: 30px;">
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field
            v-model="username"
            type="digit"
            name="帐号"
            label="帐号"
            placeholder="帐号"
            :rules="[{ required: true, message: '请填写帐号' }]"
          />
        </van-cell-group>
        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit">添 加</van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import { friendListStore } from '@/stores/mqttStore'
import { showSuccessToast, showFailToast } from 'vant';


const router = useRouter()
const username = ref(null)
const { list } = storeToRefs(friendListStore())

const onClickLeft = () => {
  router.push({
    path: '/user'
  })
}

const onSubmit = (values) => {
  const data = list.value.find(i => i.uid === username.value)
  if(data){
    showFailToast('用户已添加');
    return
  }
  list.value.push({
    "avatar":"https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg",
    "uid": username.value
  })
  showSuccessToast('添加成功');
};
</script>